import {request} from '../../utils/request'
let isTime = false
Page({

  /**
   * 页面的初始数据
   */
  data: { 
    placeholderContent:'', // 初始数据
    searchContent:"",  // 默认数据
    hotList:[],    // 热搜榜
    searchList:[],   // 搜搜内容列表
    historyList:[]  // 历史记录
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
     // 初始化数据
    this.initData()
     // 热搜榜
    this.hotSearch()
  },
  // 初始化数据
  async initData(){
    // 历史纪录显示
    const historyList = wx.getStorageSync('searchhistory')  
    if(historyList){
      this.setData({ historyList })
    }
    let res = await request("/search/default") 
    this.setData({ placeholderContent:res.data.showKeyword })
  },
  // 热搜榜
  async hotSearch(){
    let res = await request("/search/hot/detail")  
    this.setData({ hotList:res.data })
  }, 
  // 搜索 
  handleInputChange(e){ 
      let  keywords = e.detail.value.trim() 
      this.setData({searchContent:keywords})
      if(isTime){
        return
      } 
      isTime = true
      this.searchFun(keywords)
      setTimeout(async () => { 
        isTime = false
      }, 300); 
  },
  // 搜索数据的功能函数
 async searchFun(keywords){
   let { searchContent,historyList } = this.data 
   if(!keywords){
     this.setData({ searchList:[] })
     return
   } 

    let res = await request("/search",{ keywords,limit:10 }) 
    if( historyList.indexOf(searchContent) != -1 ){
      historyList.splice(historyList.indexOf(searchContent),1) 
    }
    historyList.unshift(searchContent) 
     
    this.setData({ 
      searchList:res.result.songs,
      historyList
    })
    // 历史记录放在本地缓存
    wx.setStorageSync('searchhistory', historyList)
 },

  // 删除历史记录
 deleteSearchHistory(){
   wx.showModal({
     content: '确认删除吗?',
     success:(res)=>{ 
      if(res.confirm){
         wx.clearStorageSync("searchhistory")
         this.setData({ historyList:[] })
      }
     }
   })
   
 },
 
 // 清空文本框
 clearSearchContent(){ 
   console.log(111);
   this.setData({ searchContent:'',searchList:[] })
 }  
})
